package com.cx.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cx.entity.user.MemberUserEntity;
import com.cx.utils.CommonUtil;
import com.cx.utils.ConfigUtil;
import com.cx.utils.JsonUtil;

public class SSOIntercepetor extends HandlerInterceptorAdapter{
	private static final String SUCCESS_Login = "Logon";//登陆成功标志
	private static final String FAIL_Login = "failed";//登录失败
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uri = ConfigUtil.getString("login_url", null);//登录页面路径
		String login_sso = ConfigUtil.getString("login_sso_url", null);//单点登录请求
		//在配置中获取cookie名
		String cookieName = ConfigUtil.getString("cookieName", null);
		//定义返回结果
		String result = FAIL_Login;
		String reqUrl = request.getRequestURL().toString();
		Cookie[] cookies =  request.getCookies();
		if(!CommonUtil.isEmpty(cookies)){
			for (int i = 0; i < cookies.length; i++) {
				if(cookies[i].getName().equals(cookieName)){
					String cookieID = cookies[i].getValue();
					request.getSession().setAttribute("newCookieID", cookieID);
					//返回用户对象的json字符串
					result = dealLogin(cookieID,login_sso);
				}
			}
		}
		if(result.equals(FAIL_Login)){
			response.sendRedirect(uri+"?goto="+reqUrl);
		}else{
			//将用户对象json字符串转换成对象保存到SSOUer中
			MemberUserEntity user = JsonUtil.jsonStringToObject(result, MemberUserEntity.class);
			//先放入session，在工具类里面通过获取session得到相应的值
			request.getSession().setAttribute("ssoUser", user);
			request.getSession().setAttribute("userId", user.getUuid());
			return true;
		}
		return true;
	}
	
	/**
	 * 
	 * @Description(功能描述)    :  处理登录
	 * @author(作者)             ：  曹轩
	 * @date (开发日期)          :  2015年10月12日 下午5:18:18 
	 * @exception                : 
	 * @param cookieID
	 * @return  String
	 */
	private String dealLogin(String cookieID,String login_sso) throws Exception{
		HttpClient httpclient = new HttpClient();
		PostMethod postMethod = new PostMethod(login_sso);
		postMethod.setParameter("isLogin", SUCCESS_Login);
		postMethod.setParameter("newCookie", cookieID);
		try {
			httpclient.executeMethod(postMethod);
			String result = postMethod.getResponseBodyAsString();
			return result;
		} finally{
			postMethod.releaseConnection();
		}
	}
}
